package com.bluemsun.naturallanguageprocessing.service.impl;

import com.bluemsun.naturallanguageprocessing.common.ResponseCode;
import com.bluemsun.naturallanguageprocessing.common.ServerResponse;
import com.bluemsun.naturallanguageprocessing.common.TagCommon;
import com.bluemsun.naturallanguageprocessing.dao.BrowseMapper;
import com.bluemsun.naturallanguageprocessing.dao.CollectionMapper;
import com.bluemsun.naturallanguageprocessing.dao.GoodMapper;
import com.bluemsun.naturallanguageprocessing.dao.QuestionMapper;
import com.bluemsun.naturallanguageprocessing.entity.Question;
import com.bluemsun.naturallanguageprocessing.service.IQuestionService;
import com.bluemsun.naturallanguageprocessing.tools.QuestionTag;
import com.bluemsun.naturallanguageprocessing.vo.BrowseVO;
import com.bluemsun.naturallanguageprocessing.vo.PageVO;
import com.bluemsun.naturallanguageprocessing.vo.QuestionTitleVO;
import com.bluemsun.naturallanguageprocessing.vo.QuestionVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianxinyao.analysis.jieba.keyword.Keyword;
import com.qianxinyao.analysis.jieba.keyword.TFIDFAnalyzer;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("questionService")
public class QuestionServiceImpl implements IQuestionService {

    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private GoodMapper goodMapper;

    @Resource
    private BrowseMapper browseMapper;

    @Resource
    private CollectionMapper collectionMapper;

    @Override
    public ServerResponse<Object> getHotQuestionList(Integer pageNum,Integer pageSize){
        PageVO<QuestionVO> pageVO = new PageVO(pageNum,pageSize,questionMapper.count());
        List<QuestionVO> questionVOList = questionMapper.selectSimpleQuestionList(pageVO.getStartIndex(),pageSize);
        pageVO.setList(questionVOList);
        return ServerResponse.createBySuccess(ResponseCode.SUCCESS.getDesc(),pageVO);
    }

    @Override
    public ServerResponse<Object> getQuestion(Integer id,Integer userId){
        //获取问题
        Question question = questionMapper.selectByPrimaryKey(id);
        if (question == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.PARAM_ERROR.getCode(),ResponseCode.PARAM_ERROR.getDesc());
        }
        //访问次数加一
        questionMapper.setQuestionVisitNumber(id);
        //刷新热度
        Date date =new Date();
        String Answer=question.getAnswer().replaceAll("text","p");
        question.setAnswer(Answer);
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long startDateTime = 0;
            long endDateTime = 0;
            startDateTime = dateFormat.parse(dateFormat.format(question.getCreateTime())).getTime();
            endDateTime = dateFormat.parse(dateFormat.format(date)).getTime();
            double  day= (double) ((endDateTime - startDateTime) / (1000 * 3600 * 24));
            Integer a =goodMapper.queryUserGoods(0,id);
            Double hot = (question.getVisitNumber()*0.02+goodMapper.queryUserGoods(0,id)*0.03-day*0.1);
            questionMapper.setQuestionHot(id,hot);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        BrowseVO browseVO = new BrowseVO();
        //浏览记录
        //若已经浏览过覆盖浏览历史
        BrowseVO browseVO1 = browseMapper.countIsBrowse(id,userId);
        if(browseVO1!=null){
            browseVO.setId(browseVO1.getId());
            browseVO.setBrowseTime(date);
            browseMapper.update(browseVO);
        }
        else {
            browseVO.setQuestionId(id);
            browseVO.setUserId(userId);
            browseVO.setBrowseTime(date);
            browseMapper.insertOnes(browseVO);
        }
        //是否点赞
        Integer check = goodMapper.queryUserGoods(userId, id);
        //是否收藏
        //查询该用户下的所有的收藏的问题Id
        List<Integer> userCollection = collectionMapper.isUserCollection(userId);
        boolean isCollection = userCollection.contains(question.getId());
        Map<String ,Object> map = new HashMap<>();
        map.put("question",question);
        map.put("good",check);
        map.put("isCollected",isCollection);
        return ServerResponse.createBySuccess(ResponseCode.SUCCESS.getDesc(),map);
    }

    @Override
    public ServerResponse<Object> getClassifyQuestion(Integer classifyId){
        List<QuestionVO> questionVOList = questionMapper.selectClassifyQuestionList(classifyId);
        if (questionVOList.isEmpty()){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.DATASOURCE_ERROR.getCode(), ResponseCode.DATASOURCE_ERROR.getDesc());
        }
        return ServerResponse.createBySuccess(ResponseCode.SUCCESS.getDesc(),questionVOList);
    }

    @Override
    public ServerResponse<Object> addQuestion(Question question){
        int resultCount = questionMapper.insertSelective(question);
        if (resultCount == 0){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.DATASOURCE_ERROR.getCode(),ResponseCode.DATASOURCE_ERROR.getDesc());
        }
        return ServerResponse.createBySuccessMessage(ResponseCode.SUCCESS.getDesc());
    }

    @Override
    public ServerResponse<Object> deleteQuestion(Integer id){
        int resultCount = questionMapper.deleteByPrimaryKey(id);
        if (resultCount == 0){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.PARAM_ERROR.getCode(),ResponseCode.PARAM_ERROR.getDesc());
        }
        return ServerResponse.createBySuccessMessage(ResponseCode.SUCCESS.getDesc());
    }

    @Override
    public ServerResponse<Object> updateQuestion(Question question) {
        int resultCount = questionMapper.checkQuestionById(question.getId());
        if(resultCount!=0){
            int isSuccess = questionMapper.updateByPrimaryKeySelective(question);
            if(isSuccess != 0){
            return ServerResponse.createBySuccessMessage(ResponseCode.SUCCESS.getDesc());
            }
            else return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
        }
        return ServerResponse.createByErrorCodeMessage(ResponseCode.PARAM_ERROR.getCode(), ResponseCode.PARAM_ERROR.getDesc());
    }

    @Override
    public ServerResponse<Object> getQuestionChange() {
        //返回问题的数量
        int count = questionMapper.selectAllQuestionCount();
        //产生从1到count的三个随机数
        Random random = new Random();
        ArrayList<Integer> arrayList = new ArrayList<>();
        int num;
        for (int i = 0; i < 3; i++) {
            num = random.nextInt(count)+1;
            if(arrayList.contains(num)){
                i--;
                continue;
            }else
                arrayList.add(num);
        }
        List<QuestionVO> questionChange = questionMapper.getQuestionChange(arrayList);
        return ServerResponse.createBySuccess(questionChange);
    }

    @Override
    public ServerResponse<Object> fuzzySearch(String search) {
        List<QuestionVO> questionVOS = questionMapper.fuzzySearch(search);
        if (questionVOS.size()==0){
            return ServerResponse.createByErrorMessage("抱歉，您要查找的信息不存在");
        }
        return ServerResponse.createBySuccess(questionVOS);
    }

    @Override
    public ServerResponse<Object> searchQuestionsByTag(String search,Integer pageNum,Integer pageSize) {
//        search分词
//        TFIDFAnalyzer tfidfAnalyzer = new TFIDFAnalyzer();
//        List<Keyword> analyze = tfidfAnalyzer.analyze(search, 10);
//        //和后台标签比对，得到重合的标签集合
//        List<String> searchTagsList = new ArrayList<>();
//        for (Keyword keywords : analyze){
//            searchTagsList.add(keywords.getName());
//        }
//        Set<String> searchTags = new HashSet<>(searchTagsList);
//        Set<String> tags = new HashSet<>(Arrays.asList(TagCommon.strings));
//        HashSet<String> simTags = new HashSet<>();
//        //searchTags中的元素包含tags
//        for (String userTag:searchTags){
//            for (String tag:tags){
//                if(userTag.contains(tag))
//                    simTags.add(tag);
//            }
//        }
//        //根据集合去数据库查询对应的问题，返回一个问题列表，返回前5条数据
//        if(simTags.size()==0){
//            return ServerResponse.createByErrorMessage("和用户搜索的关键词相匹配的标签下的问题为空");
//        }
//        PageHelper.startPage(pageNum,pageSize);
////        List<Question> question1 = questionMapper.selectClassifyQuestionList()
//        List<Question> questions = questionMapper.searchQuestionsByTag(simTags);
//        if(questions == null || questions.size()==0){
//            return ServerResponse.createByErrorMessage("和用户搜索的关键词相匹配的标签下的问题为空");
//        }
//        //最终question
////        List<Question> questionFinal = new ArrayList<Question>();
////        Collections.sort(questions,Comparator.comparingDouble(o->o.getCorr()));
//        for(Question question:questions){
//            Question question9 =new Question();
//            List<Keyword> words = tfidfAnalyzer.analyze(question.getTitle(),10);
//            List<String> questionTagsList = new ArrayList<>();
//            for (Keyword word : words){
//                questionTagsList.add(word.getName());
//            }
//            Set<String> questionTags = new HashSet<>(questionTagsList);
////            for (String questionTag:questionTags){
////                for (String searchTag:searchTags){
////                    if(questionTag.contains(tag))
////                        simTags.add(tag);
////                }
////            }
//            double questionTagsSize=questionTags.size();
//            questionTags.retainAll(searchTags);
//            double corr =(double)questionTags.size()/(searchTags.size());
//            question.setCorr(corr);
//        }
//        Collections.sort(questions,Comparator.comparingDouble(o->-o.getCorr()));
//
//        PageInfo<Question> pageInfo = PageInfo.of(questions);
//        return ServerResponse.createBySuccess("返回推荐的问题",pageInfo);
        String baseSolrUrl ="http://101.200.193.119:8085/solr/core_demo";
        HttpSolrClient client = new HttpSolrClient.Builder(baseSolrUrl).build();
        String q="title1:"+search+"^10"+" answer:"+search;
        System.out.println(q);
        SolrQuery solrQuery = new SolrQuery();
//        String fl="id title1 answer hot visit_number myscore:sum(product(scale(query({!v='title1:\"英语\"^3  OR answer:“英语”^2'}),0,1),0.6),product(sum(product(scale(hot,0,1),0.3))))";
        solrQuery.set("q",q);
//        solrQuery.set
        //获取有多少数量的数据
        QueryResponse queryResponse1= null;
        long num=0;
        try {
            queryResponse1 = client.query(solrQuery);
            SolrDocumentList docs = queryResponse1.getResults();
            num = docs.getNumFound();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(num==0){
            return ServerResponse.createByErrorMessage("和用户搜索的关键词相匹配的标签下的问题为空");
        }
        PageVO pageVO=new PageVO(pageNum,pageSize, Math.toIntExact(num));
        solrQuery.setStart(pageVO.getStartIndex());
        solrQuery.setRows(pageSize);
        //按热度排序
        solrQuery.addSort("sum(product(scale(query({!v='title1:"+search+"^5  OR answer:"+search+"^2'}),0,1),0.7),product(sum(product(scale(hot,0,1),0.3))))", SolrQuery.ORDER.desc);
        QueryResponse queryResponse= null;
        try {
            queryResponse = client.query(solrQuery);
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<QuestionTitleVO> questionList=queryResponse.getBeans(QuestionTitleVO.class);
        List<Question> questions = new ArrayList<>();
        for(QuestionTitleVO question:questionList){
            Question question1 = new Question();
            question1.setId(Integer.parseInt(question.getId()));
            question1.setHot(question.getHot());
            question1.setCreateTime(question.getCreateTime());
            question1.setTitle(question.getTitle().get(0));
            question1.setAnswer(question.getAnswer().get(0));
            questions.add(question1);
        }
        pageVO.setList(questions);
        try {
            client.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ServerResponse.createBySuccess("返回推荐的问题",pageVO);
    }

}
